<?php

namespace Modules\User\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;
use Setting;

// 签到记录
class SignInRecord extends Model
{
	protected $guarded = [];
	protected $table = 'sign_in_records';

	protected $casts = [
        'days' => 'json',
    ];

    // 是否已签到过
    public function isSignIn($day = NULL)
    {
    	$day = $day ?: date('Y-m-d');

    	return @$this->days[$day] ? 1 : 0;
    }

    // 按连续签到次数获取奖励
    static public function getSignRewardByContinuesTimes($times)
    {
        $baseReward = @Setting::get('sys_signin')['base_reward'] ?: 0; // 基础奖励积分
        $addReward = @Setting::get('sys_signin')['add_reward'] ?: 0;   // 连续签到递增积分
        $maxReward = @Setting::get('sys_signin')['max_reward'] ?: 20;   // 连续签到上限积分

        $scoreReward = $baseReward + ($times - 1) * $addReward;

        return $scoreReward > $maxReward ? $maxReward : $scoreReward;
    }

    // 签到
    public function signIn($day = NULL) 
    {
    	$day = $day ?: date('Y-m-d');

    	if (@$this->days[$day]) {
    		ThrowException::Conflict('今天已签到过了哦~');
    	}

    	// 刷新签到记录
    	$days = $this->days;

        $scoreReward = 0;

    	$lastDay = date('Y-m-d', strtotime('-1 days'));
    	if ($lastDay === $this->last_signin) {
    		// 连续签到数 +1
    		$continuousDays = $this->last_continuous_times + 1;

            if (@Setting::get('sys_signin')['is_reward_enabled']) {
                $addScore = @Setting::get('sys_signin')['add_reward'] ?: 0;   // 连续签到递增积分
                $maxReward = @Setting::get('sys_signin')['max_reward'] ?: 20;   // 连续签到上限积分

                $scoreReward = $this->last_score_reward + $addScore;
                $scoreReward = $scoreReward > $maxReward ? $maxReward : $scoreReward;
            }
    	}
    	else {
    		// 重新计算连续签到
    		$continuousDays = 1;

            if (@Setting::get('sys_signin')['is_reward_enabled']) {
        		$baseReward = @Setting::get('sys_signin')['base_reward'] ?: 0; // 基础奖励积分
        		$scoreReward = $baseReward;
            }
    	}

    	$days[$day] = [
    		'score' => $scoreReward,
    		'continuous_times' => $continuousDays,
    	];
    	$this->update([
    		'days' => $days,
    		'last_signin' => $day,
    		'last_continuous_times' => $continuousDays,
    		'last_score_reward' => $scoreReward
    	]);

    	return [
    		$scoreReward,
    		$continuousDays
    	];
    }
}
